varying vec4 diffuse,ambient;       //! material's diffuse & ambient
varying vec3 normal, viewerVec;     //! normal vector, viewer vector
varying vec4 shadowTexCoord;
//uniform int texWidth, texHeight;  //! size of texture
uniform sampler2D lpos;             //! handler for texture storing light directions
uniform sampler2D shadowMap;
	
void main()
{
	vec3 n,halfV, R, vv, l;
	float NdotL,NdotHV;

	vec4 I, Ia, Id, Is;
	vec4 color = ambient;
	n = normalize(normal);
	vv = normalize( viewerVec );
	//I = ambient;
	vec3 lightVec;
	vec2 coords;
	vec4 texel;
	
	I = vec4( 0.0, 0.0, 0.0, 1.0 );

	for( int i = 0; i < 1; ++i )
	{
		for( int j = 0; j < 1; ++j )
		{
			float x = float(i);
			float y = float(j);

			coords = vec2( x/16.0, y/8.0);
			texel = texture2D( lpos, coords );
			lightVec = vec3( texel );
			lightVec = vec3( lightVec.r*2.0 - 0.5, lightVec.g*2.0 - 0.5, lightVec.b*2.0 - 0.5 );
			l = normalize( lightVec );
			
			NdotL = max(dot(n,l),0.0);
	
			R = 2.0 * NdotL * n - l;

			Id = diffuse * NdotL;
			Is = gl_FrontMaterial.specular * gl_LightSource[0].specular * pow( max( dot(R, vv), 0.0), gl_FrontMaterial.shininess );
			I += Id + Is;	
		}
	}

	//I.r /= 36.0; I.g /= 36.0; I.b /= 36.0;
	
	//shadowTexCoord = normalize( shadowTexCoord );
	vec4 shadowV = texture2D( shadowMap, shadowTexCoord.xy );
	float shadow = texture2D( shadowMap, shadowTexCoord.xy ).r;
	float lighted;
	
	if( shadowV.r < (shadowTexCoord.z/shadowTexCoord.w) )
		lighted = 0.5;
	else
		lighted = 1.0;

	gl_FragColor = I  * lighted;

}